'use strict';

require('sugar');

var beginCertificate = '-----BEGIN CERTIFICATE-----';
var beginCertificateLength = 27;
var endCertificate = '-----END CERTIFICATE-----';

module.exports.isPEM = function (buf) {
  if (!Buffer.isBuffer(buf)) {
    throw new Error('isPEM requires a buffer');
  }
  return (buf.toString('utf-8', 0, beginCertificateLength) === beginCertificate);
};

module.exports.convertToPEM = function (buf) {
  if (!Buffer.isBuffer(buf)) {
    throw new Error('convertToPEM requires a buffer');
  }
  var pem = [beginCertificate];
  var base64 = buf.toString('base64');
  while (base64.length > 64) {
    pem.push(base64.first(64));
    base64 = base64.from(64);
  }
  pem.push(base64);
  pem.push(endCertificate);
  return new Buffer(pem.join('\n'));
};